'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from dopplershift.collector.backends import BaseBackend, BaseBackendRequest
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from dopplershift.core.containers.mediator import getMediator

class AuthBackendRequest(BaseBackendRequest):
    auth_ident = None
    auth_value = None
    auth_login = None
    

class DefaultAuthBackend(BaseBackend, ClientFactory):
    identify = 'default'
    req_type = AuthBackendRequest
    def __init__(self, host, port, on):
        self._host = host
        self._port = int(port)
        self._on = on

    def _getDefered(self, session_id):
        '''
        '''
        d = self._proto.get(self.session_key_pattern%session_id)
        return d
    def _getUserSession(self, result, event_handler):
        '''
        result of authentication response
        '''
        raise NotImplemented
    def isAuth(self, session_id, event_handler):
        '''
        validate authenticate information and return result to event handler as AuthResponse event
        '''
        
        if not self._connected:
            return self._generate(event_handler, False)
        d = self._getDefered(session_id)
        d.addCallback(self._getUserSession, event_handler)
        d.addErrback(self._fail, event_handler)
    def _fail(self, err, event_handler):
        self._generate(event_handler, False)
    def _generate(self, event_handler, response):
        event_handler.signal("AuthResponse", response)
    def clientConnectionLost(self, connector, reason):
        print 'Auth backend lost connection.  Reason:', reason
    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason
    def buildProtocol(self, addr):
        self._connected = True
        self._proto = self.protocol()
        return self._proto
    #def connectionMade(self):
    #    self._connected = True    
    def run(self):
        reactor.connectTCP(self._host, self._port, self)
        
    
